package io.wongxd.solution.compose.custom

import androidx.compose.foundation.gestures.Orientation
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay

/**
 *
 * 打字机
 * Typewriter
 *
 * @param fixedText
 * @param animatedText
 * @param orientation
 * @param textStyle
 */
@Composable
fun Typewriter(
    fixedText: String,
    animatedText: String,
    orientation: Orientation = Orientation.Horizontal,
    textStyle: TextStyle = TextStyle(
        fontWeight = FontWeight.SemiBold,
        fontSize = 40.sp,
        letterSpacing = -(1.6).sp,
        lineHeight = 52.sp,
        color = Color.White,
    )
) {
    var _animatedText by remember { mutableStateOf("") }
    val textToDisplay = "$fixedText$_animatedText"

    LaunchedEffect(key1 = animatedText) {
        animatedText.forEachIndexed { charIndex, _ ->
            _animatedText = animatedText.substring(startIndex = 0, endIndex = charIndex + 1)
            delay(200)
            //直接通过拼接方式在200毫秒内改变显示字符串的内容
            if (charIndex + 1 < animatedText.length) {
                _animatedText += when (orientation) {
                    Orientation.Vertical -> "|"
                    Orientation.Horizontal -> "_"
                }
                delay(100)
            }

        }


    }

    Text(text = textToDisplay, style = textStyle)

}


@Preview
@Composable
private fun P() {
    val animatePartsList = remember {
        "山不在高,有仙则名.水不在深,有龙则灵."
    }

    Typewriter(
        "小时候叔叔对我说:", animatePartsList, Orientation.Vertical
    )

}
